package com.phynos.lib.common.util;
import java.security.MessageDigest;

public class MD5 {
	
	public final static String encrypt(String str) {
		byte[] result = null;
		try{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			result = md5.digest(str.getBytes());
		}catch(Exception e) {
			e.printStackTrace();
		}
		return byte2Hex(result);
	}
	public final static String encrypt(byte[] bytes) {
		byte[] result = null;
		try{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			result = md5.digest(bytes);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return byte2Hex(result);
	}
	
	public final static byte[] encryptAsBytes(byte[] bytes){
		byte[] result = null;
		try{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			result = md5.digest(bytes);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public final static String encrypt(String str, String charset) {
		byte[] result = null;
		try{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			result = md5.digest(str.getBytes(charset));
		}catch(Exception e) {
			e.printStackTrace();
		}
		return byte2Hex(result);
	}
	
	public static String byte2Hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}
	
}